<template>
  <div class="work-schedule-container">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span class="title">排班管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>
              添加排班
            </el-button>
            <el-button type="success" @click="showBatchDialog">
              <el-icon><Setting /></el-icon>
              批量设置
            </el-button>
          </div>
        </div>
      </template>

      <!-- 排班模式切换 -->
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <!-- 周排班模式 -->
        <el-tab-pane label="周排班模板" name="weekly">
          <div class="weekly-schedule">
            <h3>本周排班表</h3>
            <div class="schedule-grid">
              <div 
                v-for="(daySchedules, index) in weeklySchedule" 
                :key="index"
                class="day-column"
                :class="{ 'past-day': isWeekDayPast(index) }"
              >
                <div class="day-header">
                  <div class="day-info">
                    <span class="day-name">{{ dayNames[index] }}</span>
                    <span class="day-date" :class="{ 'past-date': isWeekDayPast(index) }">
                      {{ getCurrentWeekDate(index) }}
                      <span v-if="isWeekDayPast(index)" class="past-indicator">已过</span>
                    </span>
                  </div>
                  <div class="day-actions">
                    <el-button 
                      v-if="!isWeekDayPast(index)"
                      size="small" 
                      type="primary" 
                      text 
                      @click="showAddDialog(index + 1)"
                    >
                      添加
                    </el-button>
                    <el-dropdown 
                      v-if="!isWeekDayPast(index)"
                      @command="(command) => handleDayAction(command, index + 1)"
                    >
                      <el-button size="small" type="primary" text>
                        更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item command="copy">复制到其他天</el-dropdown-item>
                          <el-dropdown-item command="clear" divided>清空排班</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                    <el-tag v-if="isWeekDayPast(index)" type="info" size="small">
                      历史
                    </el-tag>
                  </div>
                </div>
                <div class="schedule-list">
                  <div 
                    v-for="schedule in daySchedules" 
                    :key="schedule.id"
                    class="schedule-item"
                    :class="{ 
                      'disabled': schedule.status === 0,
                      'past-schedule': isWeekDayPast(index)
                    }"
                  >
                    <div class="time-range">{{ schedule.timeRange }}</div>
                    <div class="appointments">{{ schedule.maxAppointments }}人</div>
                    <div class="status">
                      <el-tag :type="schedule.status === 1 ? 'success' : 'danger'" size="small">
                        {{ schedule.statusName }}
                      </el-tag>
                    </div>
                    <div class="actions">
                      <el-button 
                        v-if="!isWeekDayPast(index)"
                        size="small" 
                        type="primary" 
                        text 
                        @click="editSchedule(schedule)"
                      >
                        编辑
                      </el-button>
                      <el-button 
                        v-if="!isWeekDayPast(index)"
                        size="small" 
                        type="danger" 
                        text 
                        @click="deleteSchedule(schedule)"
                      >
                        删除
                      </el-button>
                      <el-tag v-if="isWeekDayPast(index)" type="info" size="small">
                        历史记录
                      </el-tag>
                    </div>
                  </div>
                  <div v-if="daySchedules.length === 0" class="empty-day" :class="{ 'past-empty': isWeekDayPast(index) }">
                    {{ isWeekDayPast(index) ? '无历史排班' : '暂无排班' }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!-- 日期排班模式 -->
        <el-tab-pane label="日期排班" name="date">
          <ScheduleCalendar
            ref="scheduleCalendarRef"
            @add-schedule="handleAddScheduleForDate"
            @edit-schedule="handleEditDateSchedule"
            @delete-schedule="handleDeleteDateSchedule"
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加/编辑排班对话框 -->
    <el-dialog 
      v-model="scheduleDialogVisible" 
      :title="isEdit ? '编辑排班' : '添加排班'"
      width="500px"
    >
      <el-form 
        ref="scheduleFormRef" 
        :model="scheduleForm" 
        :rules="scheduleRules" 
        label-width="100px"
      >
        <!-- 周排班模式显示星期几选择 -->
        <el-form-item v-if="activeTab === 'weekly'" label="星期几" prop="dayOfWeek">
          <el-select v-model="scheduleForm.dayOfWeek" placeholder="请选择星期几">
            <el-option 
              v-for="(name, index) in dayNames" 
              :key="index + 1" 
              :label="name" 
              :value="index + 1"
            />
          </el-select>
        </el-form-item>
        
        <!-- 日期排班模式显示日期选择 -->
        <el-form-item v-if="activeTab === 'date'" label="排班日期" prop="scheduleDate">
          <el-date-picker
            v-model="scheduleForm.scheduleDate"
            type="date"
            placeholder="请选择排班日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledDate"
          />
        </el-form-item>
        
        <el-form-item label="开始时间" prop="startHour">
          <el-select v-model="scheduleForm.startHour" placeholder="请选择开始时间">
            <el-option 
              v-for="hour in availableStartHours" 
              :key="hour" 
              :label="`${hour}:00`" 
              :value="hour"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="结束时间" prop="endHour">
          <el-select v-model="scheduleForm.endHour" placeholder="请选择结束时间">
            <el-option 
              v-for="hour in availableEndHours" 
              :key="hour" 
              :label="`${hour}:00`" 
              :value="hour"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="可预约人数" prop="maxAppointments">
          <el-input-number 
            v-model="scheduleForm.maxAppointments" 
            :min="1" 
            :max="50"
            placeholder="请输入可预约人数"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="scheduleForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="scheduleForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="scheduleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSchedule">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量设置对话框 -->
    <el-dialog v-model="batchDialogVisible" title="批量设置排班" width="600px">
      <div class="batch-form">
        <el-form :model="batchForm" label-width="100px">
          <el-form-item label="选择星期">
            <el-checkbox-group v-model="batchForm.selectedDays">
              <el-checkbox 
                v-for="(name, index) in dayNames" 
                :key="index + 1" 
                :label="index + 1"
              >
                {{ name }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="时间段设置">
            <div class="time-slots">
              <div 
                v-for="(slot, index) in batchForm.timeSlots" 
                :key="index"
                class="time-slot-item"
              >
                <el-select v-model="slot.startHour" placeholder="开始时间">
                  <el-option 
                    v-for="hour in hourOptions" 
                    :key="hour" 
                    :label="`${hour}:00`" 
                    :value="hour"
                  />
                </el-select>
                <span class="separator">-</span>
                <el-select v-model="slot.endHour" placeholder="结束时间">
                  <el-option 
                    v-for="hour in hourOptions" 
                    :key="hour" 
                    :label="`${hour}:00`" 
                    :value="hour"
                  />
                </el-select>
                <el-input-number 
                  v-model="slot.maxAppointments" 
                  :min="1" 
                  :max="50"
                  placeholder="人数"
                />
                <el-button 
                  type="danger" 
                  size="small" 
                  text 
                  @click="removeTimeSlot(index)"
                  :disabled="batchForm.timeSlots.length <= 1"
                >
                  删除
                </el-button>
              </div>
              <el-button type="primary" text @click="addTimeSlot">
                <el-icon><Plus /></el-icon>
                添加时间段
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBatchSchedule">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 复制排班对话框 -->
    <el-dialog v-model="copyDialogVisible" title="复制排班" width="400px">
      <div class="copy-form">
        <p>将 <strong>{{ dayNames[copyForm.fromDay - 1] }}</strong> 的排班复制到：</p>
        <el-checkbox-group v-model="copyForm.toDays">
          <el-checkbox 
            v-for="(name, index) in dayNames" 
            :key="index + 1" 
            :label="index + 1"
            :disabled="index + 1 === copyForm.fromDay"
          >
            {{ name }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="copyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCopySchedule">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Setting, ArrowDown } from '@element-plus/icons-vue'
import ScheduleCalendar from '@/components/ScheduleCalendar.vue'
import {
  getMyWeeklySchedule,
  addWorkSchedule,
  updateWorkSchedule,
  deleteWorkSchedule,
  batchSetWorkSchedules,
  copyScheduleToOtherDays,
  clearScheduleByDay,
  getOccupiedTimeSlots
} from '@/api/workSchedule'
import {
  getMyWorkScheduleDatesByDateRange,
  addWorkScheduleDate,
  updateWorkScheduleDate,
  deleteWorkScheduleDate,
  clearScheduleByDate,
  getOccupiedTimeSlotsForDate,
  copyFromWeeklyTemplate
} from '@/api/workScheduleDate'

// 响应式数据
const weeklySchedule = ref([])
const dateSchedules = ref([])
const scheduleDialogVisible = ref(false)
const batchDialogVisible = ref(false)
const copyDialogVisible = ref(false)
const isEdit = ref(false)
const scheduleFormRef = ref()
const scheduleCalendarRef = ref()

// 当前激活的标签页
const activeTab = ref('weekly')

// 日期范围选择
const selectedDateRange = ref([])

// 已排班时间段
const occupiedTimeSlots = ref([])

// 星期几名称
const dayNames = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']

// 小时选项（8-20点）
const hourOptions = Array.from({ length: 13 }, (_, i) => i + 8)

// 排班表单
const scheduleForm = reactive({
  dayOfWeek: null,
  scheduleDate: null,
  startHour: null,
  endHour: null,
  maxAppointments: 1,
  status: 1,
  remark: ''
})

// 检查时间是否与已排班冲突
const isTimeConflict = (hour, isStartTime = true) => {
  if (!scheduleForm.dayOfWeek || occupiedTimeSlots.value.length === 0) {
    return false
  }
  
  for (const slot of occupiedTimeSlots.value) {
    const [startHour, endHour] = slot
    
    if (isStartTime) {
      // 检查开始时间：如果选择的时间在已排班时间段内，则冲突
      if (hour >= startHour && hour < endHour) {
        return true
      }
      // 如果已选择了结束时间，检查是否会与已排班冲突
      if (scheduleForm.endHour && hour < scheduleForm.endHour) {
        if (hour < endHour && scheduleForm.endHour > startHour) {
          return true
        }
      }
    } else {
      // 检查结束时间：如果选择的时间在已排班时间段内，则冲突
      if (hour > startHour && hour <= endHour) {
        return true
      }
      // 如果已选择了开始时间，检查是否会与已排班冲突
      if (scheduleForm.startHour && scheduleForm.startHour < hour) {
        if (scheduleForm.startHour < endHour && hour > startHour) {
          return true
        }
      }
    }
  }
  
  return false
}

// 可选的开始时间选项
const availableStartHours = computed(() => {
  return hourOptions.filter(hour => !isTimeConflict(hour, true))
})

// 可选的结束时间选项
const availableEndHours = computed(() => {
  return hourOptions.filter(hour => {
    // 必须大于开始时间
    if (scheduleForm.startHour && hour <= scheduleForm.startHour) {
      return false
    }
    // 检查是否与已排班冲突
    return !isTimeConflict(hour, false)
  })
})

// 监听星期几变化，获取已排班时间段
watch(() => scheduleForm.dayOfWeek, async (newDayOfWeek) => {
  if (newDayOfWeek && activeTab.value === 'weekly') {
    await loadOccupiedTimeSlots(newDayOfWeek)
  } else {
    occupiedTimeSlots.value = []
  }
}, { immediate: false })

// 监听日期变化，获取已排班时间段
watch(() => scheduleForm.scheduleDate, async (newScheduleDate) => {
  if (newScheduleDate && activeTab.value === 'date') {
    await loadOccupiedTimeSlotsForDate(newScheduleDate)
  } else {
    occupiedTimeSlots.value = []
  }
}, { immediate: false })

// 监听开始时间变化，重置结束时间如果冲突
watch(() => scheduleForm.startHour, (newStartHour) => {
  if (newStartHour && scheduleForm.endHour) {
    if (newStartHour >= scheduleForm.endHour || isTimeConflict(scheduleForm.endHour, false)) {
      scheduleForm.endHour = null
    }
  }
})

// 加载指定星期几的已排班时间段
const loadOccupiedTimeSlots = async (dayOfWeek) => {
  try {
    const response = await getOccupiedTimeSlots(dayOfWeek)
    if (response && response.code === 200) {
      // 如果是编辑模式，需要排除当前编辑的排班
      let slots = response.data || []
      if (isEdit.value && currentScheduleId.value) {
        // 从当前排班数据中找到对应的时间段并排除
        const currentSchedule = weeklySchedule.value[dayOfWeek - 1]?.find(s => s.id === currentScheduleId.value)
        if (currentSchedule) {
          slots = slots.filter(slot => 
            !(slot[0] === currentSchedule.startHour && slot[1] === currentSchedule.endHour)
          )
        }
      }
      occupiedTimeSlots.value = slots
    }
  } catch (error) {
    console.error('获取已排班时间段失败:', error)
    occupiedTimeSlots.value = []
  }
}

// 加载指定日期的已排班时间段
const loadOccupiedTimeSlotsForDate = async (scheduleDate) => {
  try {
    const response = await getOccupiedTimeSlotsForDate(scheduleDate)
    if (response && response.code === 200) {
      // 如果是编辑模式，需要排除当前编辑的排班
      let slots = response.data || []
      if (isEdit.value && currentScheduleId.value) {
        // 从当前日期排班数据中找到对应的时间段并排除
        const currentSchedule = dateSchedules.value.find(s => s.id === currentScheduleId.value)
        if (currentSchedule) {
          slots = slots.filter(slot => 
            !(slot[0] === currentSchedule.startHour && slot[1] === currentSchedule.endHour)
          )
        }
      }
      occupiedTimeSlots.value = slots
    }
  } catch (error) {
    console.error('获取已排班时间段失败:', error)
    occupiedTimeSlots.value = []
  }
}

// 按日期分组的日期排班
const groupedDateSchedules = computed(() => {
  const grouped = {}
  dateSchedules.value.forEach(schedule => {
    const date = schedule.scheduleDateStr
    if (!grouped[date]) {
      grouped[date] = []
    }
    grouped[date].push(schedule)
  })
  
  // 按时间排序
  Object.keys(grouped).forEach(date => {
    grouped[date].sort((a, b) => a.startHour - b.startHour)
  })
  
  return grouped
})

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

// 获取日期对应的星期几
const getDateDayOfWeek = (dateStr) => {
  const date = new Date(dateStr)
  const dayOfWeek = date.getDay() // 0=Sunday, 1=Monday, ..., 6=Saturday
  const dayIndex = dayOfWeek === 0 ? 6 : dayOfWeek - 1 // 转换为 0=Monday, ..., 6=Sunday
  return dayNames[dayIndex]
}

// 获取当前周的日期
const getCurrentWeekDate = (dayIndex) => {
  const today = new Date()
  const currentDay = today.getDay() // 0=Sunday, 1=Monday, ..., 6=Saturday
  const mondayOffset = currentDay === 0 ? -6 : 1 - currentDay // 计算到周一的偏移
  
  const monday = new Date(today)
  monday.setDate(today.getDate() + mondayOffset)
  
  const targetDate = new Date(monday)
  targetDate.setDate(monday.getDate() + dayIndex)
  
  const month = targetDate.getMonth() + 1
  const day = targetDate.getDate()
  return `${month}/${day}`
}

// 判断当前周的某一天是否为过去的日期
const isWeekDayPast = (dayIndex) => {
  const today = new Date()
  const currentDay = today.getDay() // 0=Sunday, 1=Monday, ..., 6=Saturday
  const mondayOffset = currentDay === 0 ? -6 : 1 - currentDay // 计算到周一的偏移
  
  const monday = new Date(today)
  monday.setDate(today.getDate() + mondayOffset)
  
  const targetDate = new Date(monday)
  targetDate.setDate(monday.getDate() + dayIndex)
  
  // 设置时间为当天开始，避免时间部分的影响
  const todayStart = new Date()
  todayStart.setHours(0, 0, 0, 0)
  
  targetDate.setHours(0, 0, 0, 0)
  
  return targetDate < todayStart
}

// 表单验证规则
const scheduleRules = computed(() => {
  const baseRules = {
    startHour: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
    endHour: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
    maxAppointments: [{ required: true, message: '请输入可预约人数', trigger: 'blur' }]
  }
  
  if (activeTab.value === 'weekly') {
    baseRules.dayOfWeek = [{ required: true, message: '请选择星期几', trigger: 'change' }]
  } else {
    baseRules.scheduleDate = [{ required: true, message: '请选择排班日期', trigger: 'change' }]
  }
  
  return baseRules
})

// 批量设置表单
const batchForm = reactive({
  selectedDays: [],
  timeSlots: [
    {
      startHour: 8,
      endHour: 12,
      maxAppointments: 2
    }
  ]
})

// 复制排班表单
const copyForm = reactive({
  fromDay: 1,
  toDays: []
})

// 当前编辑的排班ID
const currentScheduleId = ref(null)

// 页面加载时获取数据
onMounted(() => {
  loadWeeklySchedule()
  // 初始化日期范围为未来7天
  const today = new Date()
  const nextWeek = new Date(today.getTime() + 7 * 24 * 60 * 60 * 1000)
  selectedDateRange.value = [
    today.toISOString().split('T')[0],
    nextWeek.toISOString().split('T')[0]
  ]
})

// 加载周排班表
const loadWeeklySchedule = async () => {
  try {
    const response = await getMyWeeklySchedule()
    if (response && response.code === 200) {
      weeklySchedule.value = response.data
    } else {
      const errorMessage = response?.message || '获取排班数据失败'
      ElMessage.error(errorMessage)
    }
  } catch (error) {
    console.error('获取排班数据失败:', error)
    const errorMessage = error.response?.data?.message || error.message || '获取排班数据失败'
    ElMessage.error(errorMessage)
  }
}

// 显示添加排班对话框
const showAddDialog = async (dayOfWeek = null) => {
  isEdit.value = false
  currentScheduleId.value = null
  resetScheduleForm()
  if (dayOfWeek) {
    scheduleForm.dayOfWeek = dayOfWeek
    await loadOccupiedTimeSlots(dayOfWeek)
  }
  scheduleDialogVisible.value = true
}

// 编辑排班
const editSchedule = async (schedule) => {
  isEdit.value = true
  currentScheduleId.value = schedule.id
  Object.assign(scheduleForm, {
    dayOfWeek: schedule.dayOfWeek,
    startHour: schedule.startHour,
    endHour: schedule.endHour,
    maxAppointments: schedule.maxAppointments,
    status: schedule.status,
    remark: schedule.remark || ''
  })
  await loadOccupiedTimeSlots(schedule.dayOfWeek)
  scheduleDialogVisible.value = true
}

// 删除排班
const deleteSchedule = async (schedule) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除 ${schedule.dayOfWeekName} ${schedule.timeRange} 的排班吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteWorkSchedule(schedule.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadWeeklySchedule()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除排班失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 提交排班表单
const submitSchedule = async () => {
  try {
    await scheduleFormRef.value.validate()
    
    // 验证时间逻辑
    if (scheduleForm.startHour >= scheduleForm.endHour) {
      ElMessage.error('开始时间必须小于结束时间')
      return
    }
    
    let response
    if (activeTab.value === 'weekly') {
      // 周排班模式
      response = isEdit.value 
        ? await updateWorkSchedule(currentScheduleId.value, scheduleForm)
        : await addWorkSchedule(scheduleForm)
    } else {
      // 日期排班模式
      response = isEdit.value 
        ? await updateWorkScheduleDate(currentScheduleId.value, scheduleForm)
        : await addWorkScheduleDate(scheduleForm)
    }
    
    if (response && response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
      scheduleDialogVisible.value = false
      if (activeTab.value === 'weekly') {
        loadWeeklySchedule()
      } else {
        // 刷新日历数据
        scheduleCalendarRef.value?.refreshData()
      }
    } else {
      const errorMessage = response?.message || '操作失败'
      ElMessage.error(errorMessage)
    }
  } catch (error) {
    console.error('提交排班失败:', error)
    // 显示更详细的错误信息
    const errorMessage = error.response?.data?.message || error.message || '操作失败'
    ElMessage.error(errorMessage)
  }
}

// 重置排班表单
const resetScheduleForm = () => {
  Object.assign(scheduleForm, {
    dayOfWeek: null,
    scheduleDate: null,
    startHour: null,
    endHour: null,
    maxAppointments: 1,
    status: 1,
    remark: ''
  })
  occupiedTimeSlots.value = []
  nextTick(() => {
    scheduleFormRef.value?.clearValidate()
  })
}

// 显示批量设置对话框
const showBatchDialog = () => {
  batchForm.selectedDays = []
  batchForm.timeSlots = [
    {
      startHour: 8,
      endHour: 12,
      maxAppointments: 2
    }
  ]
  batchDialogVisible.value = true
}

// 添加时间段
const addTimeSlot = () => {
  batchForm.timeSlots.push({
    startHour: 8,
    endHour: 12,
    maxAppointments: 2
  })
}

// 删除时间段
const removeTimeSlot = (index) => {
  batchForm.timeSlots.splice(index, 1)
}

// 提交批量设置
const submitBatchSchedule = async () => {
  if (batchForm.selectedDays.length === 0) {
    ElMessage.error('请选择至少一个星期几')
    return
  }
  
  // 验证时间段
  for (const slot of batchForm.timeSlots) {
    if (!slot.startHour || !slot.endHour || !slot.maxAppointments) {
      ElMessage.error('请完善所有时间段信息')
      return
    }
    if (slot.startHour >= slot.endHour) {
      ElMessage.error('开始时间必须小于结束时间')
      return
    }
  }
  
  try {
    // 构建批量数据
    const schedules = []
    for (const day of batchForm.selectedDays) {
      for (const slot of batchForm.timeSlots) {
        schedules.push({
          dayOfWeek: day,
          startHour: slot.startHour,
          endHour: slot.endHour,
          maxAppointments: slot.maxAppointments,
          status: 1,
          remark: ''
        })
      }
    }
    
    const response = await batchSetWorkSchedules(schedules)
    if (response.code === 200) {
      ElMessage.success('批量设置成功')
      batchDialogVisible.value = false
      loadWeeklySchedule()
    } else {
      ElMessage.error(response.message || '批量设置失败')
    }
  } catch (error) {
    console.error('批量设置失败:', error)
    ElMessage.error('批量设置失败')
  }
}

// 处理日期操作
const handleDayAction = (command, dayOfWeek) => {
  if (command === 'copy') {
    copyForm.fromDay = dayOfWeek
    copyForm.toDays = []
    copyDialogVisible.value = true
  } else if (command === 'clear') {
    clearDaySchedule(dayOfWeek)
  }
}

// 清空日期排班
const clearDaySchedule = async (dayOfWeek) => {
  try {
    await ElMessageBox.confirm(
      `确定要清空 ${dayNames[dayOfWeek - 1]} 的所有排班吗？`,
      '确认清空',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await clearScheduleByDay(dayOfWeek)
    if (response.code === 200) {
      ElMessage.success('清空成功')
      loadWeeklySchedule()
    } else {
      ElMessage.error(response.message || '清空失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空排班失败:', error)
      ElMessage.error('清空失败')
    }
  }
}

// 提交复制排班
const submitCopySchedule = async () => {
  if (copyForm.toDays.length === 0) {
    ElMessage.error('请选择要复制到的星期几')
    return
  }
  
  try {
    const response = await copyScheduleToOtherDays({
      fromDay: copyForm.fromDay,
      toDays: copyForm.toDays
    })
    
    if (response.code === 200) {
      ElMessage.success('复制成功')
      copyDialogVisible.value = false
      loadWeeklySchedule()
    } else {
      ElMessage.error(response.message || '复制失败')
    }
  } catch (error) {
    console.error('复制排班失败:', error)
    ElMessage.error('复制失败')
  }
}

// 标签页切换
const handleTabChange = (tabName) => {
  activeTab.value = tabName
  if (tabName === 'date' && selectedDateRange.value.length === 2) {
    loadDateSchedules()
  }
}

// 加载日期排班数据
const loadDateSchedules = async () => {
  if (!selectedDateRange.value || selectedDateRange.value.length !== 2) {
    ElMessage.error('请选择日期范围')
    return
  }
  
  try {
    const [startDate, endDate] = selectedDateRange.value
    const response = await getMyWorkScheduleDatesByDateRange(startDate, endDate)
    if (response && response.code === 200) {
      dateSchedules.value = response.data || []
    } else {
      const errorMessage = response?.message || '获取日期排班数据失败'
      ElMessage.error(errorMessage)
    }
  } catch (error) {
    console.error('获取日期排班数据失败:', error)
    const errorMessage = error.response?.data?.message || error.message || '获取日期排班数据失败'
    ElMessage.error(errorMessage)
  }
}

// 日期范围变化
const handleDateRangeChange = (dateRange) => {
  selectedDateRange.value = dateRange
}

// 显示添加日期排班对话框
const showAddDateDialog = async (date) => {
  isEdit.value = false
  currentScheduleId.value = null
  resetScheduleForm()
  scheduleForm.scheduleDate = date
  await loadOccupiedTimeSlotsForDate(date)
  scheduleDialogVisible.value = true
}

// 编辑日期排班
const editDateSchedule = async (schedule) => {
  isEdit.value = true
  currentScheduleId.value = schedule.id
  Object.assign(scheduleForm, {
    scheduleDate: schedule.scheduleDateStr,
    startHour: schedule.startHour,
    endHour: schedule.endHour,
    maxAppointments: schedule.maxAppointments,
    status: schedule.status,
    remark: schedule.remark || ''
  })
  await loadOccupiedTimeSlotsForDate(schedule.scheduleDateStr)
  scheduleDialogVisible.value = true
}

// 删除日期排班
const deleteDateSchedule = async (schedule) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除 ${schedule.scheduleDateStr} ${schedule.timeRange} 的排班吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteWorkScheduleDate(schedule.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadDateSchedules()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除日期排班失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 清空日期排班
const clearDateSchedule = async (date) => {
  try {
    await ElMessageBox.confirm(
      `确定要清空 ${date} 的所有排班吗？`,
      '确认清空',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await clearScheduleByDate(date)
    if (response.code === 200) {
      ElMessage.success('清空成功')
      loadDateSchedules()
    } else {
      ElMessage.error(response.message || '清空失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空日期排班失败:', error)
      ElMessage.error('清空失败')
    }
  }
}

// 从周排班模板复制到指定日期
const copyFromWeeklyToDate = async (date) => {
  try {
    await ElMessageBox.confirm(
      `确定要从周排班模板复制到 ${date} 吗？`,
      '确认复制',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    const response = await copyFromWeeklyTemplate(date)
    if (response.code === 200) {
      ElMessage.success('复制成功')
      loadDateSchedules()
    } else {
      ElMessage.error(response.message || '复制失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('从模板复制失败:', error)
      ElMessage.error('复制失败')
    }
  }
}

// 显示日期批量设置对话框
const showDateBatchDialog = () => {
  ElMessage.info('日期批量设置功能开发中...')
}

// 显示从周模板复制对话框
const showCopyFromWeeklyDialog = () => {
  ElMessage.info('批量从模板复制功能开发中...')
}

// 日历组件事件处理
const handleAddScheduleForDate = async (date, prefilledData = null) => {
  isEdit.value = false
  currentScheduleId.value = null
  resetScheduleForm()
  scheduleForm.scheduleDate = date
  
  // 如果有预填充数据，使用预填充数据
  if (prefilledData) {
    Object.assign(scheduleForm, prefilledData)
  }
  
  await loadOccupiedTimeSlotsForDate(date)
  scheduleDialogVisible.value = true
}

const handleEditDateSchedule = async (schedule) => {
  isEdit.value = true
  currentScheduleId.value = schedule.id
  Object.assign(scheduleForm, {
    scheduleDate: schedule.scheduleDateStr,
    startHour: schedule.startHour,
    endHour: schedule.endHour,
    maxAppointments: schedule.maxAppointments,
    status: schedule.status,
    remark: schedule.remark || ''
  })
  await loadOccupiedTimeSlotsForDate(schedule.scheduleDateStr)
  scheduleDialogVisible.value = true
}

const handleDeleteDateSchedule = async (schedule) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除 ${schedule.scheduleDateStr} ${schedule.timeRange} 的排班吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deleteWorkScheduleDate(schedule.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      // 刷新日历数据
      scheduleCalendarRef.value?.refreshData()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除日期排班失败:', error)
      ElMessage.error('删除失败')
    }
  }
}
</script>

<style scoped>
.work-schedule-container {
  padding: 20px;
}

.page-card {
  min-height: calc(100vh - 120px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.weekly-schedule {
  margin-top: 20px;
}

.weekly-schedule h3 {
  margin-bottom: 20px;
  color: #303133;
}

.schedule-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 15px;
  min-height: 400px;
}

.day-column {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
}

.day-column.past-day {
  background: #f9f9f9;
  opacity: 0.8;
}

.day-header {
  background: #f5f7fa;
  padding: 12px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.day-column.past-day .day-header {
  background: #f0f2f5;
}

.day-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.day-name {
  font-weight: bold;
  color: #303133;
}

.day-date {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 4px;
}

.day-date.past-date {
  color: #c0c4cc;
}

.past-indicator {
  font-size: 10px;
  color: #909399;
  background: #f0f0f0;
  padding: 1px 4px;
  border-radius: 8px;
  line-height: 1.2;
}

.day-actions {
  display: flex;
  gap: 5px;
}

.schedule-list {
  padding: 10px;
  min-height: 300px;
}

.schedule-item {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 10px;
  margin-bottom: 8px;
  transition: all 0.3s;
}

.schedule-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.schedule-item.disabled {
  opacity: 0.6;
  background: #f5f7fa;
}

.schedule-item.past-schedule {
  background: #fafbfc;
  border-color: #e1e6eb;
  opacity: 0.7;
}

.schedule-item.past-schedule:hover {
  border-color: #c0c4cc;
  box-shadow: 0 2px 8px rgba(192, 196, 204, 0.1);
}

.schedule-item.past-schedule .time-range {
  color: #909399;
}

.time-range {
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.appointments {
  color: #606266;
  font-size: 14px;
  margin-bottom: 5px;
}

.status {
  margin-bottom: 8px;
}

.actions {
  display: flex;
  gap: 5px;
}

.empty-day {
  text-align: center;
  color: #909399;
  padding: 40px 0;
  font-size: 14px;
}

.empty-day.past-empty {
  color: #c0c4cc;
  font-style: italic;
}

.batch-form {
  padding: 10px 0;
}

.time-slots {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 15px;
  background: #fafafa;
}

.time-slot-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.time-slot-item:last-child {
  margin-bottom: 0;
}

.separator {
  color: #909399;
  font-weight: bold;
}

.copy-form {
  padding: 10px 0;
}

.copy-form p {
  margin-bottom: 15px;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 日期排班样式 */
.date-schedule {
  margin-top: 20px;
}

.date-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 8px;
}

.date-picker-section {
  display: flex;
  align-items: center;
  gap: 10px;
}

.quick-actions {
  display: flex;
  gap: 10px;
}

.date-schedule-list {
  min-height: 400px;
}

.empty-schedule {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.date-group {
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
}

.date-group-header {
  background: #f5f7fa;
  padding: 15px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.date-title {
  font-weight: bold;
  color: #303133;
  font-size: 16px;
}

.date-actions {
  display: flex;
  gap: 10px;
}

.date-schedule-items {
  padding: 15px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 15px;
}

@media (max-width: 1200px) {
  .schedule-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media (max-width: 768px) {
  .schedule-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
}

@media (max-width: 480px) {
  .schedule-grid {
    grid-template-columns: 1fr;
  }
}
</style> 